package mblog.base.upload.impl;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import mblog.base.context.AppContext;
import mblog.base.lang.MtonsException;
import mblog.base.upload.FileRepo;
import mblog.base.utils.FileNameUtils;
import mblog.base.utils.ImageUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

public abstract class AbstractFileRepo
  implements FileRepo
{
  private Logger log = Logger.getLogger(getClass());
  @Autowired
  protected AppContext appContext;
  protected String[] allowFiles = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" };
  
  protected void validateFile(MultipartFile file)
  {
    if ((file == null) || (file.isEmpty())) {
      throw new MtonsException("文件不能为空");
    }
    if (!checkFileType(file.getOriginalFilename())) {
      throw new MtonsException("文件格式不支持");
    }
  }
  
  protected boolean checkFileType(String fileName)
  {
    Iterator<String> type = Arrays.asList(this.allowFiles).iterator();
    while (type.hasNext())
    {
      String ext = (String)type.next();
      if (fileName.toLowerCase().endsWith(ext)) {
        return true;
      }
    }
    return false;
  }
  
  protected String getExt(String filename)
  {
    int pos = filename.lastIndexOf(".");
    return filename.substring(pos + 1);
  }
  
  protected void checkDirAndCreate(File file)
  {
    if (!file.getParentFile().exists()) {
      file.getParentFile().mkdirs();
    }
  }
  
  public String store(MultipartFile file, String basePath)
    throws IOException
  {
    validateFile(file);
    
    String path = basePath + FileNameUtils.genPathAndFileName(getExt(file.getOriginalFilename()));
    File temp = new File(getRoot() + path);
    checkDirAndCreate(temp);
    file.transferTo(temp);
    return path;
  }
  
  public String storeScale(MultipartFile file, String basePath, int maxWidth)
    throws Exception
  {
    validateFile(file);
    
    String path = basePath + FileNameUtils.genPathAndFileName(getExt(file.getOriginalFilename()));
    
    String dest = getRoot() + path;
    ImageUtils.scaleImageByWidth(file, dest, maxWidth);
    return path;
  }
  
  public String storeScale(MultipartFile file, String basePath, int width, int height)
    throws Exception
  {
    validateFile(file);
    
    String path = basePath + FileNameUtils.genPathAndFileName(getExt(file.getOriginalFilename()));
    

    String dest = getRoot() + path;
    ImageUtils.scaleByCenter(file, dest, width, height);
    return path;
  }
  
  public int[] imageSize(String storePath)
  {
    String root = getRoot();
    
    File dest = new File(root + storePath);
    int[] ret = new int[2];
    try
    {
      BufferedImage src = ImageIO.read(dest);
      int w = src.getWidth();
      int h = src.getHeight();
      
      ret = new int[] { w, h };
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
    return ret;
  }
  
  public void deleteFile(String storePath)
  {
    File file = new File(getRoot() + storePath);
    if ((file.exists()) && (!file.isDirectory()))
    {
      file.delete();
      this.log.info("fileRepo delete " + storePath);
    }
  }
}
